package com.cash.app.utils.extra.tools

import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import com.cash.app.utils.extra.ExtraInfoUtils
import com.cash.app.utils.extra.model.NetWorkData
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.net.NetworkInterface
import java.util.Collections

object NetWorkUtils {
    /**
     * @param wifiInfos
     * @return
     */
    fun getNetWorkInfo(wifiInfos: NetWorkData): NetWorkData {
        val mWifiManager: WifiManager = ExtraInfoUtils.getApp().getApplicationContext().getSystemService(
            Context.WIFI_SERVICE
        ) as WifiManager
        val info: WifiInfo = mWifiManager.getConnectionInfo()
        wifiInfos.current_wifi.bssid = info.getBSSID()
        val ssid: String = info.getSSID().replace("\"", "")
        wifiInfos.current_wifi.name = ssid
        wifiInfos.current_wifi.ssid = ssid
        wifiInfos.current_wifi.mac = info.getMacAddress()
        wifiInfos.ip = int2ip(info.getIpAddress())
        wifiInfos.configured_wifi.addAll(aroundWifiDeciceInfo)
        return wifiInfos
    }

    fun int2ip(ipInt: Int): String {
        val sb = StringBuilder()
        sb.append(ipInt and 0xFF).append(".")
        sb.append((ipInt shr 8) and 0xFF).append(".")
        sb.append((ipInt shr 16) and 0xFF).append(".")
        sb.append((ipInt shr 24) and 0xFF)
        return sb.toString()
    }

    val aroundWifiDeciceInfo: List<NetWorkData.NetWorkInfo>
        get() {
            val wifiLists: List<NetWorkData.NetWorkInfo> = ArrayList<NetWorkData.NetWorkInfo>()
            //        WifiManager mWifiManager = (WifiManager) ExtraInfoUtils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        List<ScanResult> scanResults = mWifiManager.getScanResults();//搜索到的设备列表
//        for (ScanResult scanResult : scanResults) {
//            wifiLists.add(new NetWorkData.NetWorkInfo(scanResult.BSSID, scanResult.SSID, scanResult.SSID));
//        }
            return wifiLists
        }

    val macAddress: String?
        get() {
            var mac: String? = "02:00:00:00:00:00"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                //Android Q（Android 10），禁止第三方应用读取设备唯一标识(IMEI,MAC等)。
            } else {
                mac = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    macDefault
                } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    macAddresss
                } else {
                    macFromHardware
                }
            }

            return mac
        }


    private val macDefault: String?
        get() {
            var mac = "02:00:00:00:00:00"

            val wifi: WifiManager = ExtraInfoUtils.getApp().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE) as WifiManager
            if (wifi == null) {
                return mac
            }
            var info: WifiInfo? = null
            try {
                info = wifi.getConnectionInfo()
            } catch (e: Exception) {
            }
            if (info == null) {
                return null
            }
            mac = info.getMacAddress()
            if (!TextUtils.isEmpty(mac)) {
                mac = mac.uppercase()
            }
            return mac
        }

    private val macAddresss: String
        get() {
            var WifiAddress = "02:00:00:00:00:00"
            try {
                WifiAddress =
                    BufferedReader(FileReader(File("/sys/class/net/wlan0/address")))
                        .readLine()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return WifiAddress
        }


    private val macFromHardware: String
        get() {
            try {
                val all: List<NetworkInterface> =
                    Collections.list(NetworkInterface.getNetworkInterfaces())
                for (nif in all) {
                    if (!nif.name.equals("wlan0", ignoreCase = true)) continue

                    val macBytes = nif.hardwareAddress ?: return ""

                    val res1 = StringBuilder()
                    for (b in macBytes) {
                        res1.append(String.format("%02X:", b))
                    }

                    if (res1.length > 0) {
                        res1.deleteCharAt(res1.length - 1)
                    }
                    return res1.toString()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return "02:00:00:00:00:00"
        }


    val bluetoothMac: String?
        get() {
            var bluetoothAddress: String? = ""
            bluetoothAddress = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                Settings.Secure.getString(
                    ExtraInfoUtils.getApp().getContentResolver(), "bluetooth_address"
                )
            } else {
                getBluetoothAddressSdk23(BluetoothAdapter.getDefaultAdapter())
            }
            return bluetoothAddress
        }

    private fun <BluetoothAdapter> getBluetoothAddressSdk23(adapter: BluetoothAdapter?): String? {
        if (adapter == null) return null
        val btAdapterClass: Class<out BluetoothAdapter?> = adapter.javaClass
        try {
            val btClass = Class.forName("android.bluetooth.IBluetooth")
            val bluetooth = btAdapterClass.getDeclaredField("mService")
            bluetooth.isAccessible = true
            val btAddress = btClass.getMethod("getAddress")
            btAddress.isAccessible = true
            return btAddress.invoke(bluetooth[adapter]) as String
        } catch (e: Exception) {
            return ""
        }
    }
}
